
//弹出登录
var Login = (function(login) {
    var isInclude = false,
        _$dom = {};
    login.login = function (update) {
       return new Login(update);
    }

    function Login (update) {
        this.callback = update || null;
        this.isEnableCode = false; //是否显示code;
        this.isLogin = false;//是否正在登录
    }


    Login.prototype = {
        dialogLogin : function (){
            if (!isInclude) {
                this.createDom();
                isInclude = true;
            }
            this.init();
            this.bindEvent();
            this.open();
        },
        //初始化数据
        init:function(){
            this.errorTips();
            _$dom.name.val('');
            _$dom.pwd.val('');
            _$dom.code.val('');
            _$dom.codeWrap.hide();
        },
        //创建弹出框登录节点
        createDom: function(){
            var _this = this;
            var _$wrap = $('<div class="dialog-class"></div>');
            var _$userWrap = $('<div class="l-wrap"></div>'),
            // _$label = $('<p>用户名</p>'),
            _$userInput = $('<input type="text" placeholder="用户名/手机号/邮箱" class="d-user placeholder"/>');
            _$userWrap.append(_$label)
                .append(_$userInput);
            _$wrap.append(_$userWrap);
            var _$pwdWrap = $("<div class='l-wrap'></div>"),
            // _$label = $('<p><span>密码</span><a href="'+base+'/forget/index.jhtml" target="_blank" class="forget-pwd">忘记密码？</a></p>'),
            _$pwdInput = $('<input type="password" placeholder="密码" class="d-pwd placeholder"/>');
            _$pwdWrap.append(_$label)
                .append(_$pwdInput);
            _$wrap.append(_$pwdWrap); 

            var _$codeWrap = $("<div class='l-wrap code-wrap'></div>"),
            // _$label = $('<p><span>验证码</span></p>'),
            _$codeInput = $("<input type='text' class='dialog-code' placeholder='验证码'/>");
            _$img = $('<img src="" class="code-img" />');
            _$refresh = $('<a href="javascript:;">看不清？</a>');
            _$codeWrap.append(_$label)
                .append(_$codeInput)
                .append(_$img)
                .append(_$refresh);
            _$wrap.append(_$codeWrap);


            var _$rememberWrap = $("<p></p>"),
            _$label = $('<label for="remember">自动登录</label>'),
            _$remberInput = $('<input type="checkbox" class="d-remember" id="remember"/>');
            _$forget = $('<a href="'+base+'/forget/index.jhtml" target="_blank" class="forget-pwd">忘记密码？</a>'),

            _$label.prepend(_$remberInput)
                .append(_$forget);

            _$rememberWrap.append(_$label);


            _$wrap.append(_$rememberWrap);
          
            var _$loginBtn = $('<input type="button" value="登录" class="dialog-login-btn"/>');
            _$wrap.append(_$loginBtn);
            var _$register = $('<p class="d-register"><a href="'+base+'/register.jhtml" target="_blank">免费注册</a></p>');
            _$wrap.append(_$register);

            var _$error = $("<div class='error-tips'></div>");
            _$wrap.prepend(_$error);
            _$dom = {
                wrap: _$wrap,
                name: _$userInput,
                pwd : _$pwdInput,
                btn : _$loginBtn,
                error: _$error,
                codeWrap:  _$codeWrap,
                code : _$codeInput,
                img : _$img,
                refresh : _$refresh,
                rember: _$remberInput
            }
            
            var rm = $.cookie("rm");
			if (rm != undefined && rm != '') {
				_$userInput.val(rm);
				_$pwdInput.focus();
			} else {
				_$userInput.focus();
			}
        },
        //打开登录框
        open : function(){
            this.dialog = oDialog.dialogElem({
                content: _$dom.wrap,
                title: '登录',
                cancelValue: '关闭'
            });
        },
        //关闭登录框
        close: function(){
           this.dialog || this.dialog.close();
        },
        //绑定登录事件
        bindEvent: function(){
            var _this = this;

             _$dom.img.unbind('click').bind('click', function() {
                _this.refresh();
            });
             _$dom.refresh.unbind('click').bind('click', function(){
                _this.refresh();
            })
            _$dom.wrap.find('input').unbind('keydown').bind('keydown', function(event) {
                event = event || window.event;
                if (event.keyCode == 13) {
                    _this.loginEvent();
                }
            })
            _$dom.btn.unbind('click').bind('click', function() {
                _this.loginEvent();
            })
        },
        //登录事件
        loginEvent: function(){
                if (this.isLogin) return false;
                var name = $.trim(_$dom.name.val());
                var pwd = $.trim(_$dom.pwd.val());
                var code = this.isEnableCode ? $.trim(_$dom.code.val()) : '';
                var sErr = {message:'', wrap: null};

                if (!name.length) {
                    sErr.message = '用户名不能为空';
                    sErr.wrap = _$dom.name;
                }
                if (!sErr.message.length && !pwd.length) {
                    sErr.message = '密码不能为空';
                    sErr.wrap = _$dom.pwd;
                }

                if (this.isEnableCode && !sErr.message && !code.length) {
                    sErr.message = '验证码不能为空';
                    sErr.wrap = _$dom.code;
                }

                if (sErr.message.length) {
                    sErr.wrap.focus();
                    this.errorTips(sErr.message);
                    return false;
                }

                this.errorTips();
                this.isLogin = true;
                this.httpLogin(name, pwd, code, !!_$dom.wrap.find('.d-remember:checked').length);

        },
        //登录完成
        success: function(){
            this.close();
            if (this.callback) this.callback();
            else location.reload();
        },
        //错误提示
        errorTips: function(message) {
            _$dom.error.html(message || '')[message ? 'show' : 'hide']();
        },
        //显示验证码输入框
        enableCode: function() {
            this.isEnableCode = true;
            _$dom.codeWrap.show();
            this.refresh();
        },
        //刷新验证码
        refresh: function(){
            _$dom.img.attr("src", base + "/captcha.jhtml?captchaId=${captchaId}&timestamp=" + new Date().getTime());
        },
        httpLogin: function(username, password, code,rember) {
            var _this = this;
            ajax({
                    url : base + "/publicKey.jhtml",
                    type : "GET",
                    dataType : "json",
                    cache : false,
                    showError : true,
                    loading : '正在登录...',
                    beforeSend: function(){
                        _$dom.btn.val('正在登录...');
                    },
                    success : function(data) {
                        var rsaKey = new RSAKey();
                        rsaKey.setPublic(b64tohex(data.modulus), b64tohex(data.exponent));
                        password = hex2b64(rsaKey.encrypt(password));
                        $.ajax({
                            url : base + "/loginVerify.jhtml",
                            type : "POST",
                            dataType : "json",
                            data : {
                                username : username,
                                password : password,
                                captcha : code,
                                captchaId : "${captchaId}",
                                remember : rember
                            },
                            cache : false,
                            success : function(data) {
                                if (data.error == undefined || data.error == '') {
                                    _this.success();
                                } else {
                                   _this.errorTips(data.error.replace('，请重新输入', ''));
                                    if (data.showCode) {
                                        _this.enableCode();
                                    }
                                }
                            }
                        });
                    },
                    complete: function(){
                        _$dom.btn.val('登录');
                        _this.isLogin = false;
                    }
                }); 
        }
    }
    return login;
})( Login || {})

function ajax(options){
	var p = options || {};
    var url = p.url;
    $.ajax({
        cache: false,
        async: p.async == undefined ? true : p.async,
        url: url,
        data: p.data,
        dataType: p.dataType || 'json', 
        traditional:true,
        type: p.type || 'POST',
        beforeSend: function () {
        	if(options.beforeSend){
        		options.beforeSend();
        	}
        },
        complete: function () {
        	if (options.complete) {
        		options.complete();
        	}
        },
        success: function (result) {
			if (p.success){
				p.success(result);
			}else{
				oDialog.alert(result.msg);
			}
        },
        
        error: function (xhr,status) {



        	//报错时，不执行complete
        	options.loading = false;
        	var showError = p.showError || true;
        	
        	if(p.error){
        		p.error(xhr,status);
        	}
        	if(xhr.status == 403){
				// window.location = base + "/login.jhtml";
                Login.login().dialogLogin();
                

        	}else if(showError){
                if (options.error) {
                    options.error();
                }


    			if(xhr.status == 400){
    				var responseError = eval(xhr.responseText);
    				var info = '';
    				for(var i = 0;i < responseError.length;i++){
    					info += responseError[i] + '<br/>';
    				}
                    if(!("undefined" == typeof layer)) {
                        layer.alert(info);
                    }else{
                        oDialog.alert(info, true);
                    }
    			}else{
    				alert('系统出错');
    			}
        	}


            ;
        }
    });
}




